﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using KingSite.Library.Security;

namespace KingSite.Library.Cache.FileCacheWrapper {
    public class FileCacheWrapper : CacheBase, ICache {
        FileCache fc = null;    
        public FileCacheWrapper() {
            fc = FileCache.GetInstance("FileCachePath");
        }

        public void Add(string key, object value) {
            Add(key, value, -1);  
        }

        public void Add(string key, object value, int seconds) {
            DateTime now = DateTime.Now.ToUniversalTime();
            CacheItem item;
            if (seconds >= 0) {
                item = new CacheItem(value, now.AddSeconds(seconds));
            }
            else {
                item = new CacheItem(value, now.AddYears(10));
            }
            string hashkey = GetHashKey(key);
            Remove(hashkey);
            fc.Add(hashkey, item);
        }

        public object Get(string key) {
            string hashkey = GetHashKey(key);
            object tmp = fc.Get(hashkey);
            if (tmp == null) {
                return null;
            }
            CacheItem item = tmp as CacheItem;
            if (item.ExpiryDate <= DateTime.Now.ToUniversalTime()) {
                Remove(key);
                return null;
            }
            return item.Item;
        }

        public void Remove(string key) {
            string hashkey = GetHashKey(key);
            fc.Remove(hashkey);
        }

        public void Clear() {
            fc.Clear();
        }
    }

}
